package com.anlu.session;

import com.anlu.session.utils.CookieBasedSession;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * request 的封装类
 */
public class MyRequestWrapper extends HttpServletRequestWrapper {
    private volatile boolean committed = false;
    private String uuid = UUID.randomUUID().toString();

    private RedisTemplate redisTemplate;
    private MySession mySession;

    public MyRequestWrapper(HttpServletRequest request,RedisTemplate redisTemplate) {
        super(request);
        this.redisTemplate = redisTemplate;
    }

    public void commitSession(){
        if(committed){
            return;
        }
        committed=true;

        MySession session = this.getSession();
        if(session!=null && null!=session.getAttrs()){
            redisTemplate.opsForHash().putAll(session.getId(),session.getAttrs());
        }
    }


    public MySession createSession() {
        String sessionId = CookieBasedSession.getRequestSessionId(this);
        Map<String,Object> attr;
        if(null!=sessionId){
            attr = redisTemplate.opsForHash().entries(sessionId);
        }else{
            System.out.println("create session by rId:"+uuid);
            sessionId = UUID.randomUUID().toString();
            attr = new HashMap<>();
        }

        mySession = new MySession();
        mySession.setId(sessionId);
        mySession.setAttrs(attr);
        return mySession;
    }

    /**
     * 取session
     * @return
     */
    public MySession getSession() {
        if (null != mySession){
            return mySession;
        }
        return this.createSession();
    }

    /**
     * 是否已登陆
     * @return
     */
    public boolean isLogin(){
        Object user = getSession().getAttribute(SessionFilter.USER_INFO);
        return null != user;
    }


}
